<template>
    <div class="teacherDialog">
        <el-dialog append-to-body v-model="teacherDialog" title="班级老师" width="700">
            <div class="searchTeacher">
                <el-input @keyup.enter="handleEnter" v-model.trim="searchTeacher" style="width: 490px"
                    placeholder="请输入被邀请老师的手机号，按回车「Enter」搜索" />
                <el-button @click="handleEnter" style="margin-left:15px" type="primary">搜索</el-button>
            </div>


            <div v-if="oprateStatus" class="teachNum">
                <span class="iconfont icon-Customermanagement"></span>
                班级老师({{ bindTeachList.length }}人)
            </div>

            <div v-else class="teachNum">
                <span class="iconfont icon-Customermanagement"></span>
                老师({{ teacherList.length }}人)
            </div>

            <div class="teacherList">
                <!-- 已绑定的老师列表 -->
                <el-row v-for="(item, index) in bindTeachList " v-if="oprateStatus">
                    <el-col :span="8">
                        <div class="userInfo">
                            <el-avatar :size="40" :src="item.avatar || defaultAvatar" />
                            <div class="right">
                                <div class="userName">{{ item.nick_name }}
                                    <span style="font-size: 12px; color: #666;
                                font-weight: 400;">({{ item.user_name }})</span>
                                </div>
                                {{ item.mobile }}
                            </div>
                        </div>
                    </el-col>

                    <el-col :span="4">
                        <div class="tab" v-if="useUserStore().rolesName == '管理组'">
                            <el-switch @change="switchChange(item)" v-model="item.is_admin" class="ml-2"
                                style="--el-switch-on-color: #409EFF; --el-switch-off-color: #ccc"
                                :active-text="item.is_admin ? '主管理' : '老师'" />
                        </div>

                        <div class="tab" v-if="useUserStore().rolesName == '老师组'">
                            <el-tag v-if="item.is_admin" effect="dark" type="primary">主管理</el-tag>
                            <el-tag v-else type="primary">老师</el-tag>

                        </div>

                    </el-col>
                    <el-col :span="6">
                        <div class="joinTime">
                            {{ parseTime(item.join_time, '{y}-{m}-{d}') }}加入
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div class="delete">
                            <el-popconfirm title='确认要移除当前老师吗?' confirm-button-text='确认移除' @confirm='delOneTeach(item)'>
                                <template #reference>
                                    <el-button type="danger" link
                                        :disabled="delDisabled">
                                        <span class="iconfont icon-reduce"></span>移除
                                    </el-button>

                                </template>
                            </el-popconfirm>
                        </div>

                    </el-col>
                </el-row>
                <!-- 搜索老师列表 -->
                <el-row v-for="item in teacherList" v-else>
                    <el-col :span="8">
                        <div class="userInfo">
                            <el-avatar :size="40" :src="item.avatar || defaultAvatar" />
                            <div class="right">
                                <div class="userName">{{ item.nick_name }}<span style="font-size: 12px; color: #666;
                                font-weight: 400;">({{ item.user_name }})</span> </div>
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="10">
                        <div style="display: flex; justify-content: center; align-items: center;  height: 100%;"
                            class="mobile">
                            {{ item.mobile }}
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div class="add">
                            <el-button :disabled="item.disabled" @click="addTeachToClass(item)" type="primary" link>
                                <span class="iconfont icon-add"></span>添加
                            </el-button>
                        </div>
                    </el-col>
                </el-row>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button :disabled="confirmDisable" type="primary" @click="handleConfirm">
                        确定
                    </el-button>
                    <el-button @click="teacherDialog = false">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from "vue"
import useUserStore from '@/store/modules/user'
import { parseTime } from '@/utils/common';
import { claTeacher, bindTeacher, addTeacher, delTeacher } from "@/api/banji/classadmin"
import defaultAvatar from '@/assets/images/user-default.jpg'
import { ElMessage } from 'element-plus';
const confirmDisable=ref(true)
const delDisabled = ref(useUserStore().rolesName === "管理组" ? false : true)
const teacherDialog = ref(false)
const class_id = ref(null)
const props = defineProps({
    nodeId: {
        type: Number
    }
})

// 控制绑定老师和老师列表之间的切换
const oprateStatus = ref()

// 老师数组
const teacherList = ref([

])
// 已绑定老师数组
const bindTeachList = ref([])
console.log(props.nodeId);
// 打开对话框的方法，由父组件触发
const openDialog = async() => {
    teacherDialog.value = true
    oprateStatus.value = true
    await getbindTeacher(class_id.value)
    removeStatus()
}

const searchTeacher = ref()

// 点击确定
const handleConfirm = () => {
    // 如果有绑定老师
    if (bindTeachList.value.length > 0) {
        // 查询数据库中有没有管理员
        const adminArr = bindTeachList.value.filter(item => item.is_admin);
        if (adminArr.length == 0) {
            ElMessage.error("班级里面至少要有一个管理员")
        } else if (adminArr.length >= 2) {
            ElMessage.error("管理员只能有一个")
        } else {
            ElMessage.success("班级老师设置成功")
            teacherDialog.value = false
            confirmDisable.value=true
        }
    } else {
        teacherDialog.value = false
    }

}


// 搜索框按下回车事件
const handleEnter = () => {
    getTeacherData()
    confirmDisable.value=false
}

// 获取老师组信息
const getTeacherData = () => {
    console.log(searchTeacher.value + "..." + props.nodeId);
    claTeacher({
        class_info_id: props.nodeId,
        mobile: searchTeacher.value,
        tenant_id:useUserStore().tenant_id
    }).then(res => {
        if (!res.response) {
            compareTeach(res)
            teacherList.value = res
            oprateStatus.value = false
            return
        }
        ElMessage.error("找不到该老师")
    })
}

// 查询已绑定的老师
const getbindTeacher = async (class_id) => {
    await bindTeacher({
        class_info_id: class_id,
        tenant_id:useUserStore().tenant_id
    }).then(res => {
        

        if (res.length == 1) {
            res[0].is_admin = true

            let options = {
                "teacher_id": res[0].user_id,
                "is_admin": res[0].is_admin,
                "class_info_id": props.nodeId,
                "tenant_id":useUserStore().tenant_id
            }
            addTeacher(options).then(res => {

            })

        }
//   对班级老师进行排序
        res.sort((a, b) => {
            // 如果 a.is_admin 为 true，则应该位于 b 之前，返回负数
            // 如果 b.is_admin 为 true 而 a 不是，则 a 应该位于 b 之后，返回正数
            // 如果两者都是或者都不是 true，则保持原有顺序
            return (b.is_admin - a.is_admin);
        });
        bindTeachList.value = res
    })
}

// 将老师加入班级
const addTeachToClass = (item) => {
    let options = {
        "teacher_id": item.user_id,
        "is_admin": item.is_admin ? item.is_admin : false,// 是否为班级管理
        "class_info_id": props.nodeId,
        "tenant_id":useUserStore().tenant_id
    }
    addTeacherFun(options)
}

// 添加老师的方法
const addTeacherFun = (options) => {
    addTeacher(options).then(res => {
        console.log(res);
        if (!res) {
            ElMessage.success("加入成功")
            oprateStatus.value = true
            getbindTeacher(class_id.value)
        } else {
            ElMessage.error(res.response.data)
        }
    })
}

// 更新老师

const upTeacherFun = (options) => {
    addTeacher(options).then(res => {
        console.log(res);
        if (!res) {

        } else {
            ElMessage.error(res.response.data)
            getbindTeacher(class_id.value)
        }
    })

}



//移除一个老师
const delOneTeach = (item) => {
    if (item.user_name == useUserStore().userName) {
        ElMessage.error("不能移除自己")
        return
    }
    delTeacher(item.id).then(res => {
        console.log(res);
        if (!res) {
            ElMessage.success("移除成功")
            getbindTeacher(class_id.value)
            confirmDisable.value=false

        } else {
            ElMessage.error(res.response.data)
        }
    })
}

// switch开关改变事件
const switchChange = (item) => {
    confirmDisable.value=false
    let options = {
        "teacher_id": item.user_id,
        "is_admin": item.is_admin,// 是否为班级管理
        "class_info_id": props.nodeId,
        "tenant_id":useUserStore().tenant_id
    }
    upTeacherFun(options)


}

// 比较老师组列表中是否有老师已经绑定,添加disabled标记
const compareTeach = (teacherListArr) => {
    teacherListArr.forEach(item1 => {
        // 使用some方法检查arr2中是否有nick_name与item1匹配的项
        const isDisabled = bindTeachList.value.some(item2 => item2.nick_name === item1.nick_name);
        if (isDisabled) {
            // 如果匹配到，添加disabled属性
            item1.disabled = true;
        }
    });
}


watch(() => props.nodeId, nv => {
    class_id.value = nv

}, { immediate: true, deep: true })

defineExpose({
    openDialog

})

// 判断移除状态是否为禁用
const removeStatus=()=>{
    // 获取绑定老师种的管理员
    const bindTeachListAdmin = bindTeachList.value.filter(item => item.is_admin);
        if((bindTeachListAdmin[0].user_name==useUserStore().userName&&

        bindTeachListAdmin[0].is_admin)||useUserStore().rolesName=='管理组'){

            delDisabled.value=false
        }else{
            delDisabled.value=true
        } 
}

</script>

<style lang="scss" scoped>
.icon-Customermanagement {
    font-size: 20px;
}

.teachNum {
    display: flex;
    align-items: center;
    padding: 30px 0 10px 0;
    border-bottom: 1px solid #ccc;
}

.teacherList {
    height: 400px;
    overflow-y: auto;
    .el-row {
        padding: 20px 0 5px 0;
    }
    .userInfo {
        display: flex;
        align-items: center;

        .right {
            margin-left: 15px;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            text-align: left;

            .userName {
                font-size: 16px;
                font-weight: 900;
                color: #000;
            }

            .userPhone {
                color: #999
            }
        }
    }

    .tab {
        display: flex;
        align-items: center;
        height: 100%;
    }

    .joinTime {
        display: flex;
        justify-content: right;
        align-items: center;
        height: 100%;
    }

    .delete,
    .add {
        display: flex;
        justify-content: right;
        height: 100%;
        align-items: center;

    }


}

.dialog-footer {
    margin-top: 30px;
}
</style>